package com.sunnyweather.android.logic.network

import com.sunnyweather.android.logic.model.RealtimeResponse
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

object SunnyWeatherNetWork {

    val service = ServiceCreator.create<PlaceService>()

    val weatherService = ServiceCreator.create<WeatherService>()

    suspend fun searchPlaces(query: String) = service.searchPlace(query).await()

    suspend fun getDailyWeather(lng: String, lat: String) =
        weatherService.getDailyWeather(lng, lat).await()

    suspend fun getRealtimeWeather(lng: String, lat: String): RealtimeResponse =
        weatherService.getRealtimeWeather(lng, lat).await()

    private suspend fun <T> Call<T>.await(): T {
        return suspendCoroutine {
            enqueue(object : Callback<T> {
                override fun onResponse(call: Call<T>, response: Response<T>) {
                    val body = response.body()
                    if (body == null) it.resumeWithException(java.lang.RuntimeException("body is null"))
                    else
                        it.resume(body)
                }

                override fun onFailure(call: Call<T>, t: Throwable) {
                    it.resumeWithException(t)
                }
            })
        }
    }

//    private suspend fun <T> Call<T>.await(): T? {
//        var ans: T?
////            enqueue(object : Callback<T> {
////                override  fun onResponse(call: Call<T>, response: Response<T>) {
////
////                        ans = response.body()!!
////
////
////                }
////                override fun onFailure(call: Call<T>, t: Throwable) {
////
////                }
////            })
//        val response = execute()
//        ans = response.body()
//
//        return ans
//
//    }


}




